package com.mi.audio.lc3codec;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.ArrayList;

/**
 * @Author zhangsai
 * @CreateTime: 2024-11-15 15:07
 * @Description: TODO
 */
public class LC3Decoder {
    private final String TAG = "LC3Decoder";
    private final int mSampleRate;
    private final int mFrameSize;
    private final int mFrameDuration;
    private Handler handler = new Handler(Looper.getMainLooper());

    public LC3Decoder(int frameSize, int frameDuration, int sampleRate) {
        this.mFrameSize = frameSize;
        this.mFrameDuration = frameDuration;
        this.mSampleRate = sampleRate;
    }

    public int create() {
        return this.createDecoder(this.mFrameSize, this.mFrameDuration, this.mSampleRate);
    }


    public byte[] decode(byte[] data, int len) {
        ArrayList<Byte> pcm = new ArrayList<>();
        byte[] src = new byte[this.mFrameSize];
        for (int i = 0; i < len / this.mFrameSize; ++i) {
            System.arraycopy(data, i * this.mFrameSize, src, 0, this.mFrameSize);

            byte[] decoded = this.decode(src);
            if (decoded == null) {
                Log.e(TAG, "Failed to decode!");
                return null;
            }

            for (Byte aByte : decoded) {
                pcm.add(aByte);
            }
        }

        Log.e(TAG, "lc3 input size " + data.length + " output size " + pcm.size());

        byte[] result = new byte[pcm.size()];
        for (int i = 0; i < pcm.size(); i++) {
            result[i] = pcm.get(i);
        }


        return result;

    }


    public void destroy() {
        this.destroyDecoder();
    }


    private native int createDecoder(int frameSize, int frameDuration, int sampleRate);

    private native byte[] decode(byte[] src);

    public native int decodeFile(String input, String output);

    private native void destroyDecoder();

    static {
        System.loadLibrary("jni_lc3");
    }

}
